package app.hzvmap.com.rangecontrol.service;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import org.xutils.ex.DbException;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import app.hzvmap.com.rangecontrol.App;
import app.hzvmap.com.rangecontrol.R;
import app.hzvmap.com.rangecontrol.model.Position;
import app.hzvmap.com.rangecontrol.utils.AppSetting;
import app.hzvmap.com.rangecontrol.utils.DateUtil;
import app.hzvmap.com.rangecontrol.utils.DbHelper;
import app.hzvmap.com.rangecontrol.utils.GPSUtils;
import app.hzvmap.com.rangecontrol.utils.netty.LogPushUdpClientHandler;

public class InspectService extends Service implements AMapLocationListener {

    public AMapLocationClient locationClient = null;

    private long lastGpsTime;

    private AMapLocation lastLocation;

    private int status = 0;

    public InspectService() {
    }

    @Override
    public void onCreate() {

    }

    Handler mHandler = new Handler();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    Runnable r = new Runnable() {

        @Override
        public void run() {
            //发送心跳包 **G|1>F8151F0E91054CAFB50739C7ABE10713|20190121100637|121.305145|31.196833|11|-1|65
            if (AppSetting.getAppSetting(App.getInstance()).RUNSTATE.get() == 1) {
                try {
                    if (App.POSITION != null) {
                        LogPushUdpClientHandler.senderInternal(String.format("**G|%s>%s|%s|%.6f|%.6f|%d|%d|%d",
                                AppSetting.getAppSetting(App.getInstance()).GUID.get(), AppSetting.getAppSetting(App.getInstance()).PARTNUM.get(), App.FORMATTER.format(new Date()),
                                App.POSITION.getLongitude(), App.POSITION.getLatitude(), (int) App.POSITION.getAltitude(), (int) App.POSITION.getSpeed(), (int) App.POSITION.getBearing()), App.REMOTEADD, null);
                    } else {
                        LogPushUdpClientHandler.senderInternal(String.format("**G|%s>%s|%s|%.6f|%.6f|%d|%d|%d",
                                AppSetting.getAppSetting(App.getInstance()).GUID.get(), AppSetting.getAppSetting(App.getInstance()).PARTNUM.get(), App.FORMATTER.format(new Date()),
                                0.0, 0.0, 0, 0, 0), App.REMOTEADD, null);
                    }
                    Log.d("HTTP", "心跳");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //每隔1s循环执行run方法
                mHandler.postDelayed(this, 30000);
            }
        }
    };

    public void startAlarm() {
        /**
         首先获得系统服务
         */
        AlarmManager am = (AlarmManager)
                App.getInstance().getSystemService(Context.ALARM_SERVICE);

        /** 设置闹钟的意图，我这里是去调用一个服务，该服务功能就是获取位置并且上传*/
        Intent intent = new Intent(this, InspectService.class);
        PendingIntent pendSender = PendingIntent.getService(this, 0, intent, 0);
        am.cancel(pendSender);

        /**AlarmManager.RTC_WAKEUP 这个参数表示系统会唤醒进程；我设置的间隔时间是10分钟 */
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5 * 60 * 1000, pendSender);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (status == 1) {
            Log.i("HTTP", "服务正在运行");
        } else {
            status = 1;
            Log.d("HTTP", "start service");
            mHandler.postDelayed(r, 1000);
            try {
                if (locationClient == null) {
                    locationClient = new AMapLocationClient(this);
                    AMapLocationClientOption option = new AMapLocationClientOption();
                    option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
                    // option.setOnceLocation(true);
                    //设置定位间隔,单位毫秒,默认为5000ms
                    option.setInterval(2000);
                    option.setMockEnable(false);
                    option.setLocationCacheEnable(false);
                    option.setNeedAddress(false);
                    option.setSensorEnable(true);
                    locationClient.setLocationOption(option);
                    locationClient.setLocationListener(this);
                }
                Notification noti = null;
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    noti = new Notification.Builder(this, App.NOTIFICATION_CHANNEL_ID_SERVICE)
                            .setSmallIcon(R.mipmap.ic_launcher_round)//设置小图标
                            .setContentTitle("正在巡检中...")
                            .setContentText(getString(R.string.appname))
                            .setWhen(System.currentTimeMillis())
                            .setTicker("持续定位中")
                            .build();
                    noti.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
                } else {
                    noti = new Notification.Builder(this)
                            .setSmallIcon(R.mipmap.ic_launcher_round)//设置小图标
                            .setContentTitle("正在巡检中...")
                            .setContentText(getString(R.string.appname))
                            .setWhen(System.currentTimeMillis())
                            .setTicker("持续定位中")
                            .build();
                }
                noti.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
                startForeground(1, noti);

                AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
                //读者可以修改此处的Minutes从而改变提醒间隔时间
                int Minutes = 5 * 60 * 1000;
                //SystemClock.elapsedRealtime()表示1970年1月1日0点至今所经历的时间
                long triggerAtTime = SystemClock.elapsedRealtime() + Minutes;
                //此处设置开启AlarmReceiver这个Service
                Intent i = new Intent(this, Alarmreceiver.class);
                i.setAction("arui.alarm.action");
                PendingIntent sender = PendingIntent.getBroadcast(this, 0, i, 0);
                //ELAPSED_REALTIME_WAKEUP表示让定时任务的出发时间从系统开机算起，并且会唤醒CPU。
                manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, sender);

                if (AppSetting.getAppSetting(App.getInstance()).RUNSTATE.get() == 1) {
                    locationClient.startLocation();
                }
            } catch (Exception ex) {
                Log.e("HTTP", ex.getMessage());
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        status = 0;
        try {
            LogPushUdpClientHandler.senderInternal(String.format("**E|%s>%s",
                    AppSetting.getAppSetting(App.getInstance()).GUID.get(), App.FORMATTER.format(new Date())), App.REMOTEADD, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.unRegisterLocationListener(this);
            locationClient.stopLocation();
            if (locationClient != null) {
                locationClient.onDestroy();
                locationClient = null;
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        Log.d("HTTP", "location change");
        if (aMapLocation != null
                && aMapLocation.getErrorCode() == 0
                && lastGpsTime < aMapLocation.getTime()
                && (lastLocation == null || (aMapLocation.getLatitude() != lastLocation.getLatitude() && aMapLocation.getLongitude() != lastLocation.getLongitude()))
                && AppSetting.getAppSetting(App.getInstance()).RUNSTATE.get() == 1) {
            HashMap<String, Double> pos = GPSUtils.delta(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            try {

                if (!AppSetting.getAppSetting(this).INSPECTDAY.get().equalsIgnoreCase(DateUtil.getNowDay())) {
                    UUID uuid = UUID.randomUUID();
                    AppSetting.getAppSetting(App.getInstance()).PARTNUM.set(uuid.toString().replace("-", ""));
                }

                lastGpsTime = aMapLocation.getTime();
                lastLocation = aMapLocation;
                Position position = new Position();
                position.setBearing(aMapLocation.getBearing());
                position.setSpeed(aMapLocation.getSpeed());
                position.setAltitude(aMapLocation.getAltitude());
                position.setTime(DateUtil.timeStamp2Date(aMapLocation.getTime(), ""));
                position.setTel(AppSetting.getAppSetting(App.getInstance()).ACCOUNT.get());
                position.setLongitude(pos.get("lon"));
                position.setLatitude(pos.get("lat"));
                position.setGuid(AppSetting.getAppSetting(App.getInstance()).PARTNUM.get());
                App.getInstance().POSITION = position;
                DbHelper.getDb().save(position);
            } catch (DbException e) {
                Log.e("HTTP", e.getMessage());
            }
        }
    }

}
